<!-- components/AssignmentStudent.vue -->
<template>
  <div class="assignment-container">
    <el-card class="assignment-card">
      <template #header>
        <div class="card-header">
          <h3>作业列表</h3>
        </div>
      </template>

      <!-- 作业列表 -->
      <el-table
        :data="assignments"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        border
        stripe>
        <el-table-column prop="title" label="作业标题" min-width="200">
          <template #default="{ row }">
            <div class="assignment-title">
              <span>{{ row.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="due_date" label="截止日期" width="180">
          <template #default="{ row }">
            <div class="due-date">
              <i class="el-icon-time"></i>
              {{ formatDate(row.due_date) }}
              <el-tag
                size="small"
                :type="isExpired(row.due_date) ? 'danger' : 'success'"
                class="time-tag">
                {{ getRelativeTime(row.due_date) }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="满分" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.score }}分</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="提交状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                v-if="row.status !== 'SUBMITTED'"
                type="primary"
                size="small"
                :disabled="isExpired(row.due_date)"
                @click="openSubmitDialog(row)">
                提交作业
              </el-button>
              <el-button
                v-else
                type="success"
                size="small"
                @click="openSelfSubmissionDialog(row.id)">
                查看提交
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="viewAssignmentDetail(row.id)">
                作业详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 已提交作业内容弹窗 -->
    <el-dialog
      v-model="submissionDialogVisible"
      title="已提交作业内容"
      width="60%"
      :before-close="handleClose"
      class="submission-dialog"
    >
      <div v-if="submissionDetail" class="submission-detail">
        <el-descriptions title="提交信息" :column="2" border>
          <el-descriptions-item label="学号">{{ submissionDetail.student.id }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ submissionDetail.student.username }}</el-descriptions-item>
          <el-descriptions-item label="作业标题">{{ submissionDetail.assignment_title }}</el-descriptions-item>
          <el-descriptions-item label="课程名称">{{ submissionDetail.course_name }}</el-descriptions-item>
          <el-descriptions-item label="提交时间">{{ formatDate(submissionDetail.submitted_at) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(submissionDetail.status)">
              {{ getStatusText(submissionDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="成绩" :span="2">
            {{ submissionDetail.grade !== null ? `${submissionDetail.grade}分` : '未评分' }}
          </el-descriptions-item>
          <el-descriptions-item label="教师反馈" :span="2">
            {{ submissionDetail.feedback || '暂无反馈' }}
          </el-descriptions-item>
        </el-descriptions>

        <el-form :model="submitForm" label-width="100px" class="submission-form">
          <el-form-item label="作业内容">
            <el-input
              type="textarea"
              v-model="submitForm.content"
              rows="6"
              placeholder="请输入作业内容"
            ></el-input>
          </el-form-item>

          <el-form-item label="现有附件">
            <div class="attachment-list">
              <div v-for="attachment in submissionDetail.attachments"
                   :key="attachment.id"
                   class="attachment-item">
                <el-link
                  :href="attachment.file_path + '?download'"
                  :download="getFileName(attachment.file_path)"
                  type="primary">
                  <i class="el-icon-document"></i>
                  {{ getFileName(attachment.file_path) }}
                </el-link>
                <div class="attachment-info">
                  <span class="upload-time">上传时间: {{ formatDate(attachment.uploaded_at) }}</span>
                  <el-button
                    type="danger"
                    size="small"
                    circle
                    @click="deleteAttachment(attachment.id)">
                    <i class="el-icon-delete"></i>
                  </el-button>
                </div>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="添加新附件">
            <el-upload
              class="assignment-upload"
              drag
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :file-list="submitForm.fileList"
              multiple
            >
              <el-icon><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽文件到此处或 <em>点击上传</em>
              </div>
              <template #tip>
                <div class="el-upload__tip">
                  支持任意格式文件，单个文件不超过10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitStudentAssignmentForUpdate">
            更新提交
          </el-button>
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 作业详情弹窗 -->
    <AssignmentDetailDialog
      v-model:visible="detailDialogVisible"
      :assignment="assignmentDetail"
      @close="handleDetailClose"
    />

    <!-- 提交作业弹窗 -->
    <el-dialog
      v-model="submitDialogVisible"
      title="提交作业"
      width="60%"
      class="submit-dialog"
    >
      <el-form
        ref="submitFormRef"
        :model="submitForm"
        :rules="submitRules"
        label-width="100px">
        <el-form-item
          label="作业内容"
          prop="content"
          :rules="[{ required: true, message: '请输入作业内容', trigger: 'blur' }]"
        >
          <el-input
            type="textarea"
            v-model="submitForm.content"
            rows="6"
            placeholder="请输入作业内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="附件上传">
          <el-upload
            class="assignment-upload"
            drag
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="submitForm.fileList"
            multiple
          >
            <el-icon><upload-filled /></el-icon>
            <div class="el-upload__text">
              拖拽文件到此处或 <em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持任意格式文件，单个文件不超过10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitStudentAssignment">
            提交作业
          </el-button>
          <el-button @click="submitDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import AssignmentDetailDialog from '@/components/assignment/AssignmentDetailDialog.vue'

const props = defineProps({
  courseId: {
    type: [String, Number],
    required: true
  }
})
const isExpired = (dueDate) => {
  if (!dueDate) return false
  return new Date(dueDate) < new Date()
}

// 获取相对时间
const getRelativeTime = (dueDate) => {
  if (!dueDate) return ''

  const now = new Date()
  const due = new Date(dueDate)

  // 先判断是否过期（需要精确到时间）
  if (now > due) {
    return '已过期'
  }

  // 其他情况只需要比较日期，重置时间为当天 00:00:00
  const todayStart = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const dueStart = new Date(due.getFullYear(), due.getMonth(), due.getDate())

  // 计算日期差（不考虑时分秒）
  const diffTime = dueStart - todayStart
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return '今天截止'
  } else if (diffDays === 1) {
    return '明天截止'
  } else {
    return `还剩 ${diffDays} 天`
  }
}
// 状态管理
const assignments = ref([])
const submitDialogVisible = ref(false)
const submissionDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentAssignment = ref(null)
const submissionDetail = ref(null)
const assignmentDetail = ref(null)
const submitFormRef = ref(null)
const submitForm = reactive({
  content: '',
  fileList: []
})

const submitRules = {
  content: [
    { required: true, message: '请输入作业内容', trigger: 'blur' },
    { min: 10, message: '作业内容不能少于10个字符', trigger: 'blur' }
  ]
}

// 工具函数
const getStatusType = (status) => {
  const types = {
    'SUBMITTED': 'success',
    'NOT_SUBMITTED': 'warning',
    'GRADED': 'primary'
  }
  return types[status] || 'info'
}

const getStatusText = (status) => {
  const texts = {
    'SUBMITTED': '已提交',
    'NOT_SUBMITTED': '未提交',
    'GRADED': '已批改'
  }
  return texts[status] || '未知状态'
}

const getFileName = (filePath) => {
  return filePath.split('/').pop()
}

// API调用函数
const fetchAssignments = async () => {
  try {
    const response = await axios.get(`/backend/api/assignment/course/${props.courseId}/list/`, {
      withCredentials: true
    })
    assignments.value = response.data
  } catch (error) {
    console.error('获取作业列表失败:', error)
    ElMessage.error('获取作业列表失败，请稍后重试')
  }
}

const submitStudentAssignment = async () => {
  if (!submitFormRef.value) return

  await submitFormRef.value.validate(async (valid) => {
    if (!valid) return

    try {
      const formData = new FormData()
      formData.append('content', submitForm.content)
      submitForm.fileList.forEach(file => {
        formData.append('files', file.raw)
      })

      const response = await axios.post(
        `/backend/api/assignment/${currentAssignment.value.id}/submit/`,
        formData,
        {
          headers: { 'Content-Type': 'multipart/form-data' },
          withCredentials: true
        }
      )

      if (response.status === 200 || response.status === 201) {
        ElMessage.success('作业提交成功')
        submitDialogVisible.value = false
        await fetchAssignments()
      }
    } catch (error) {
      console.error('提交作业失败:', error)
      ElMessage.error('提交作业失败，请稍后重试')
    }
  })
}

const submitStudentAssignmentForUpdate = async () => {
  try {
    // 更新提交内容
    const contentResponse = await axios.patch(
      `/backend/api/assignment/submission/${submissionDetail.value.id}/update_content/`,
      { content: submitForm.content },
      { withCredentials: true }
    )

    if (contentResponse.status === 200) {
      // 如果有新的附件，上传它们
      if (submitForm.fileList.length > 0) {
        const formData = new FormData()
        submitForm.fileList.forEach(file => {
          formData.append('files', file.raw)
        })

        await axios.post(
          `/backend/api/assignment/submission/${submissionDetail.value.id}/upload_attachments/`,
          formData,
          {
            headers: { 'Content-Type': 'multipart/form-data' },
            withCredentials: true
          }
        )
      }

      ElMessage.success('作业更新成功')
      submissionDialogVisible.value = false
      await fetchAssignments()
    }
  } catch (error) {
    console.error('更新作业失败:', error)
    ElMessage.error('更新作业失败，请稍后重试')
  }
}

const deleteAttachment = async (attachmentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个附件吗？此操作不可撤销。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await axios.delete(
      `/backend/api/assignment/submission/attachment/${attachmentId}/delete/`,
      { withCredentials: true }
    )
if (response.status === 200) {
        ElMessage.success('附件删除成功')
        await fetchSubmissionDetail(currentAssignment.value.id)
      }
    } catch (error) {
      if (error === 'cancel') return
      console.error('删除附件失败:', error)
      ElMessage.error('删除附件失败，请稍后重试')
    }
  }

const fetchSubmissionDetail = async (assignmentId) => {
  try {
    const response = await axios.get(`/backend/api/assignment/${assignmentId}/submission/`, {
      withCredentials: true
    })
    submissionDetail.value = response.data
    submitForm.content = response.data.content
    submitForm.fileList = []
    submissionDialogVisible.value = true
  } catch (error) {
    console.error('获取作业提交详情失败:', error)
    ElMessage.error('获取作业提交详情失败，请稍后重试')
  }
}

const fetchAssignmentDetail = async (assignmentId) => {
  try {
    const response = await axios.get(`/backend/api/assignment/${assignmentId}/detail/`, {
      withCredentials: true
    })
    assignmentDetail.value = response.data
    detailDialogVisible.value = true
  } catch (error) {
    console.error('获取作业详情失败:', error)
    ElMessage.error('获取作业详情失败，请稍后重试')
  }
}

// 事件处理函数
const handleFileChange = (file, fileList) => {
  submitForm.fileList = fileList
}

const handleClose = () => {
  submissionDialogVisible.value = false
  submitForm.content = ''
  submitForm.fileList = []
}

const handleDetailClose = () => {
  detailDialogVisible.value = false
}

const openSubmitDialog = (assignment) => {
  if (isExpired(assignment.due_date)) {
    ElMessage.warning('该作业已过截止日期，无法提交')
    return
  }

  currentAssignment.value = assignment
  submitForm.content = ''
  submitForm.fileList = []
  submitDialogVisible.value = true
}

const openSelfSubmissionDialog = (assignmentId) => {
  currentAssignment.value = assignments.value.find(a => a.id === assignmentId)
  fetchSubmissionDetail(assignmentId)
}

const viewAssignmentDetail = (assignmentId) => {
  fetchAssignmentDetail(assignmentId)
}
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}`
}
// 生命周期钩子
onMounted(() => {
  fetchAssignments()
})
</script>

<style scoped>
.assignment-container {
  padding: 20px;
}

.assignment-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #303133;
  font-size: 18px;
}

.assignment-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.due-date {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #606266;
}

.time-tag {
  margin-left: auto;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-start;
  align-items: center;
}

.submission-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.submission-detail {
  .el-descriptions {
    margin-bottom: 20px;
  }
}

.submission-form {
  margin-top: 20px;
}

.attachment-list {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 10px;
  background-color: #f8f9fa;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border-bottom: 1px solid #ebeef5;

  &:last-child {
    border-bottom: none;
  }

  .attachment-info {
    display: flex;
    align-items: center;
    gap: 10px;

    .upload-time {
      color: #909399;
      font-size: 13px;
    }
  }
}

.assignment-upload {
  :deep(.el-upload-dragger) {
    width: 100%;
  }

  .el-upload__tip {
    color: #909399;
    font-size: 12px;
    margin-top: 8px;
  }
}

.submit-dialog {
  .el-dialog__body {
    padding: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 20px;
}

:deep(.el-table) {
  th {
    background-color: #f5f7fa !important;
  }

  td {
    padding: 8px 0;
  }
}

:deep(.el-tag) {
  text-align: center;
  min-width: 65px;
}

:deep(.el-descriptions__cell) {
  padding: 12px 20px;
}
</style>